package com.sbtr.impl;


import com.sbtr.business.calibration.service.*;
import com.sbtr.business.material.service.IMaterialInfoService;
import com.sbtr.business.project.service.IProjectService;
import com.sbtr.constant.CalibrationConstant;
import com.sbtr.open.calibration.dto.*;
import com.sbtr.open.material.dto.MaterialInfoDto;
import com.sbtr.open.project.dto.ProjectDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 训练数据处理service
 *
 * @author wangwh15
 */
@Service
public class MaterialInfoCommon {

    private static final Logger logger = LoggerFactory.getLogger(MaterialInfoCommon.class);
    private static final String REGEX = "\\r\\n"; //分隔符，中文分号
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IMaterialInfoService materialInfoService;
    @Autowired
    private CalibrationTxtCommon calibrationTxtCommon;
    @Autowired
    private CalibrationPictureCommon calibrationPictureCommon;
    @Autowired
    private CalibrationVoiceCommon calibrationVoiceCommon;
    @Autowired
    private ICalibrationTxtEntityService calibrationTxtEntityService;
    @Autowired
    private ICalibrationImgService calibrationImgService;
    @Autowired
    private ICalibrationObjectDetectionImgBoxService calibrationObjectDetectionImgBoxService;
    @Autowired
    private ICalibrationVoiceService calibrationVoiceService;
    @Autowired
    private ICalibrationTxtService calibrationTxtService;
    @Autowired
    private ICalibrationFileService calibrationFileService;
    @Autowired
    private ICalibrationService calibrationService;

//	@Autowired
//	private CalibrationTxtMapper calibrationTxtMapper;

    //	//    @Value("${minio.bucketName}")
//	private String bucketName="test";
    @Autowired
    private ICalibrationDetailsService calibrationDetailsService;
    @Value("${oss.config.uploadPath}")
    private String uploadPath;

    private static boolean isMessyCode(String strName) {
        try {
//			if(strName.length() >= 30){
//				strName = strName.substring(0, 30);
//			}

            Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
            Matcher m = p.matcher(strName);
            String after = m.replaceAll("");
            String temp = after.replaceAll("\\p{P}", "");
            temp = temp.replaceAll("[\\u00A0]+", "");
            temp = temp.replaceAll("\uFEFF", "");
            String regEx = "[\n`~!@#$%^&*￣()+=|{}':;',\\[\\].<>/?~！@#￥%……&*()——+|{}【】‘；：”“’。， 、？]";
            temp = temp.replaceAll(regEx, "");
            char[] ch = temp.trim().toCharArray();

//			int length = (ch != null) ? ch.length : 0;
//			if(length >= 30){
//				length = 30;
//			}
            int length = ch.length;
            for (int i = 0; i < length; i++) {
                char c = ch[i];
                if (!Character.isLetterOrDigit(c)) {
                    String str = "" + ch[i];
                    if (!str.matches("[\u4e00-\u9fa5]+")) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 数据标注模块：生成建模数据
     *
     * @param calibrationDto
     * @param dto
     * @return
     */
    public MaterialInfoDto generateImageData(CalibrationDto calibrationDto, GenerateDataDto dto) {

        //获取所有图片标签名和路径
        List<CalibrationImgDto> calibrationImgDtoList = calibrationImgService.findCompletedByCalibrationId(dto.getCalibrationId());

        String fileType = calibrationDto.getTaskType();
        String creater = calibrationDto.getCreater();
        String otherName = UUID.randomUUID().toString().replaceAll("-", "");

        String bucketDir = uploadPath + "/" + fileType + "/" + creater;
        //生成所有对应文件夹和图片,并压缩成zip
        String resultFilePath = calibrationPictureCommon.createResultFile(calibrationImgDtoList, bucketDir + "/" + otherName);

        String fileName = dto.getFileName();
        String fileDesc = dto.getFileDesc();

        // 将标注数据打包，生成到建模数据集表中
        MaterialInfoDto materialInfoDto = new MaterialInfoDto();
        materialInfoDto.setBucketDir(bucketDir);
        materialInfoDto.setFileType(fileType);
        materialInfoDto.setFileDesc(fileDesc);
        materialInfoDto.setFileName(fileName);
        materialInfoDto.setFileName2(otherName + ".zip");
        materialInfoDto.setCreater(creater);
        materialInfoDto.setFileSize(Long.toString(new File(resultFilePath).length()));
        materialInfoDto.setCreateTime(new Date());
        materialInfoService.save(materialInfoDto);
        return materialInfoDto;
    }

    public MaterialInfoDto generateTxtData(CalibrationDto calibrationDto, GenerateDataDto dto) {
        List<CalibrationTxtDto> hasCalibratedTxt = calibrationTxtService.searchHasCalibratedByIds(dto.getCalibrationId());


        String fileName = dto.getFileName();
        String fileDesc = dto.getFileDesc();
        String fileType = calibrationDto.getTaskType();
        String creater = calibrationDto.getCreater();
        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + ".txt";
        String newName = fileType + "/" + creater + "/" + otherName;

        File outFile = new File(uploadPath + "/" + newName);

        String bucketDir = uploadPath + "/" + fileType + "/" + creater;

        File sourceParent = outFile.getParentFile();
        if (!sourceParent.exists()) {
            sourceParent.mkdirs();
        }

        Writer out;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile, true), StandardCharsets.UTF_8), 10240);
            out.write("comment" + "\t" + "label" + "\r\n");
            for (int i = 0; i < hasCalibratedTxt.size(); i++) {
                out.write(
                        hasCalibratedTxt.get(i).getTxtContent() +
                                "\t" + hasCalibratedTxt.get(i).getClassifyName()
                                + "\r\n");
            }
            out.flush();
            out.close();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


        MaterialInfoDto materialInfoDto = new MaterialInfoDto();

        materialInfoDto.setBucketDir(bucketDir);
        materialInfoDto.setFileType(fileType);
        materialInfoDto.setFileDesc(fileDesc);
        materialInfoDto.setFileName(fileName);
        materialInfoDto.setFileName2(otherName);
        materialInfoDto.setCreater(creater);
        materialInfoDto.setCreateTime(new Date());
        materialInfoDto.setFileSize(Long.toString(outFile.length()));
        materialInfoService.save(materialInfoDto);

        return materialInfoDto;
    }

    /**
     * 生成图像检查的数据集
     *
     * @param calibrationDto 任务
     * @return
     */
    public MaterialInfoDto generateImageDectionData(CalibrationDto calibrationDto, GenerateDataDto dto) {
        /**
         * 一个主任务可能有多个calibrationFile,生成的数据集应该和主任务id绑定,而不是calibrationFile
         *
         * calibrationId-->  已标注的calibraionImg  -->图片复制到数据集的目录  -->更新json.txt   -->  集体打zip包   --> 保存MaterialInfoDto
         */

        String fileName = dto.getFileName();
        String fileDesc = dto.getFileDesc();
        List<CalibrationImgDetectDto> imgList = this.calibrationObjectDetectionImgBoxService.findCompletedByCalibrationId(calibrationDto.getId());
        String fileType = calibrationDto.getTaskType();
        String creater = calibrationDto.getCreater();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String bucketDir = uploadPath + "/" + fileType + "/" + creater;

        //生成所有对应文件夹和图片,并压缩成zip
        String newZipFileName = "dataset_" + calibrationDto.getId() + "_" + uuid;
        String datasetBaseDir = bucketDir + File.separator + newZipFileName;//数据集目录
        //生成数据集zip包
        String zipFilePath = calibrationPictureCommon.createImgDetectMaterialZip(imgList, datasetBaseDir);
        logger.info("@123****:" + datasetBaseDir + "，已压缩成>>>>>>" + zipFilePath);


        //新增数据集对象（保存zip包路径）
        MaterialInfoDto materialInfoDto = new MaterialInfoDto();
        materialInfoDto.setBucketDir(bucketDir);
        materialInfoDto.setFileType(calibrationDto.getTaskType());
        materialInfoDto.setFileDesc(fileDesc);
        materialInfoDto.setFileName(fileName);
        materialInfoDto.setFileName2(newZipFileName + ".zip");
        materialInfoDto.setCreater(calibrationDto.getCreater());
        materialInfoDto.setFileSize(Long.toString(new File(zipFilePath).length()));
        materialInfoDto.setCreateTime(new Date());
        materialInfoService.save(materialInfoDto);
        return materialInfoDto;
    }

    public MaterialInfoDto generateTxtEntityData(CalibrationDto calibrationDto, GenerateDataDto dto) {
        List<CalibrationTxtEntityDto> hasCalibratedTxt = calibrationTxtEntityService.searchHasCalibratedByIds(dto.getCalibrationId());

        String fileName = dto.getFileName();
        String fileDesc = dto.getFileDesc();
        String fileType = calibrationDto.getTaskType();
        String creater = calibrationDto.getCreater();
        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + ".txt";
        String newName = fileType + "/" + creater + "/" + otherName;

        File outFile = new File(uploadPath + "/" + newName);

        String bucketDir = uploadPath + "/" + fileType + "/" + creater;

        File sourceParent = outFile.getParentFile();
        if (!sourceParent.exists()) {
            sourceParent.mkdirs();
        }

        Writer out;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile, true), StandardCharsets.UTF_8), 10240);
            out.write("comment" + "\t" + "label" + "\r\n");
            for (CalibrationTxtEntityDto calibrationTxtEntityDto : hasCalibratedTxt) {
                out.write(
                        calibrationTxtEntityDto.getTxtContent() +
                                "\t" + calibrationTxtEntityDto.getTxtJson()
                                + "\r\n");
            }
            out.flush();
            out.close();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


        MaterialInfoDto materialInfoDto = new MaterialInfoDto();

        materialInfoDto.setBucketDir(bucketDir);
        materialInfoDto.setFileType(fileType);
        materialInfoDto.setFileDesc(fileDesc);
        materialInfoDto.setFileName(fileName);
        materialInfoDto.setFileName2(otherName);
        materialInfoDto.setCreater(creater);
        materialInfoDto.setCreateTime(new Date());
        materialInfoDto.setFileSize(Long.toString(outFile.length()));
        materialInfoService.save(materialInfoDto);

        return materialInfoDto;
    }

    public MaterialInfoDto generateVoiceData(CalibrationDto calibrationDto, GenerateDataDto dto) {

        //获取所有图片标签名和路径
        List<CalibrationVoiceDto> calibrationVoiceDtoList = calibrationVoiceService.findCompletedByCalibrationId(dto.getCalibrationId());

        String fileType = calibrationDto.getTaskType();
        String creater = calibrationDto.getCreater();
        String otherName = UUID.randomUUID().toString().replaceAll("-", "");
        String bucketDir = uploadPath + "/" + fileType + "/" + creater;
        //生成所有对应文件夹和图片,并压缩成zip
        String resultFilePath = calibrationVoiceCommon.createResultFile(calibrationVoiceDtoList, bucketDir + "/" + otherName);

        String fileName = dto.getFileName();
        String fileDesc = dto.getFileDesc();

        MaterialInfoDto materialInfoDto = new MaterialInfoDto();

        materialInfoDto.setBucketDir(bucketDir);
        materialInfoDto.setFileType(fileType);
        materialInfoDto.setFileDesc(fileDesc);
        materialInfoDto.setFileName(fileName);
        materialInfoDto.setFileName2(otherName + ".zip");
        materialInfoDto.setCreater(creater);
        materialInfoDto.setFileSize(Long.toString(new File(resultFilePath).length()));
        materialInfoDto.setCreateTime(new Date());
        materialInfoService.save(materialInfoDto);
        return materialInfoDto;
    }

    public String createImageData(CalibrationDto calibrationDto) {
        //获取所有图片标签名和路径
        List<CalibrationImgDto> calibrationImgDtoList = calibrationImgService.findCompletedByCalibrationId(calibrationDto.getId());
        //生成所有对应文件夹和图片,并压缩成zip
        String creater = calibrationDto.getCreater();
        String fileType = calibrationDto.getTaskType();
        String bucketDir = uploadPath + "/" + "NewCalibration/" + fileType + "/" + creater + "/" + UUID.randomUUID().toString().replaceAll("-", "");
        String resultFilePath = calibrationPictureCommon.createResultFile(calibrationImgDtoList, bucketDir);
        return resultFilePath;
    }

    public File createTxtData(CalibrationDto calibrationDto) {
        List<CalibrationTxtDto> hasCalibratedTxt = calibrationTxtService.searchHasCalibratedByIds(calibrationDto.getId());


        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + ".txt";

        String creater = calibrationDto.getCreater();
        String taskType = calibrationDto.getTaskType();

        File outFile = new File(uploadPath + "/" + "NewCalibration/" + taskType + "/" + creater);
        boolean results = outFile.mkdirs();
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        outFile = new File(uploadPath + "/" + "NewCalibration/" + taskType + "/" + creater + "/" + otherName);


        Writer out;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile, true), StandardCharsets.UTF_8), 10240);
            out.write("comment" + "\t" + "label" + "\r\n");
            for (int i = 0; i < hasCalibratedTxt.size(); i++) {
                out.write(
                        hasCalibratedTxt.get(i).getTxtContent() +
                                "\t" + hasCalibratedTxt.get(i).getClassifyName()
                                + "\r\n");
            }
            out.flush();
            out.close();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return outFile;
    }

    /**
     * 下载总任务标定的素材数据（文件和框框信息）
     *
     * @param calibrationDto
     * @param
     */
    public File createImageDectionData(CalibrationDto calibrationDto) {

        List<CalibrationImgDetectDto> imgList = calibrationObjectDetectionImgBoxService.findCompletedByCalibrationId(calibrationDto.getId());
        String fileType = calibrationDto.getTaskType();
        String creater = calibrationDto.getCreater();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String bucketDir = uploadPath + "/" + fileType + "/" + creater;

        //生成所有对应文件夹和图片,并压缩成zip
        String newZipFileName = "dataset_" + calibrationDto.getId() + "_" + uuid + ".zip";
        String datasetBaseDir = bucketDir + File.separator + "dataset_" + calibrationDto.getId() + "_" + uuid;//数据集目录
        //生成数据集zip包
        String zipFilePath = calibrationPictureCommon.createImgDetectMaterialZip(imgList, datasetBaseDir);
        logger.info("@123****:" + datasetBaseDir + "，已压缩成>>>>>>" + zipFilePath);
        //1.找到解压路径 path
        //String unzipPath = imgList.get(0).getBaseDir();

        //3.将素材重新打成zip包，返回文件流
        //List<CalibrationImgDto> calibrationImgDtoList = BeanCopyUtils.copyProperties(imgList,CalibrationImgDto.class);
        //String resultFilePath = calibrationPictureService.createImgDetectMaterialZip(imgList, unzipPath);
        return new File(zipFilePath);
    }

    public File createTxtEntityData(CalibrationDto calibrationDto) {
        List<CalibrationTxtEntityDto> hasCalibratedTxt = calibrationTxtEntityService.searchHasCalibratedByIds(calibrationDto.getId());


        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + ".txt";

        String creater = calibrationDto.getCreater();
        String taskType = calibrationDto.getTaskType();

        File outFile = new File(uploadPath + "/" + "NewCalibration/" + taskType + "/" + creater);
        boolean results = outFile.mkdirs();
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        outFile = new File(uploadPath + "/" + "NewCalibration/" + taskType + "/" + creater + "/" + otherName);


        Writer out;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile, true), StandardCharsets.UTF_8), 10240);
            out.write("comment" + "\t" + "result" + "\r\n");
            for (CalibrationTxtEntityDto calibrationTxtEntityDto : hasCalibratedTxt) {
                out.write(
                        calibrationTxtEntityDto.getTxtContent() +
                                "\t" + calibrationTxtEntityDto.getTxtJson()
                                + "\r\n");
            }
            out.flush();
            out.close();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return outFile;
    }

    public String createVoiceData(CalibrationDto calibrationDto) {
        //获取所有图片标签名和路径
        List<CalibrationVoiceDto> calibrationVoiceDtoList = calibrationVoiceService.findCompletedByCalibrationId(calibrationDto.getId());

        //生成所有对应文件夹和图片,并压缩成zip
        String creater = calibrationDto.getCreater();
        String fileType = calibrationDto.getTaskType();
        String bucketDir = uploadPath + "/" + "NewCalibration/" + fileType + "/" + creater + "/" + UUID.randomUUID().toString().replaceAll("-", "");
        String resultFilePath = calibrationVoiceCommon.createResultFile(calibrationVoiceDtoList, bucketDir);
        return resultFilePath;
    }

    /**
     * 下载个人任务标定的素材数据（文件和框框信息）
     *
     * @param calibrationDto
     * @param finisher
     */
    public File createImageDectionData(CalibrationDto calibrationDto, String finisher) {
        //calibrationId -> calibrationFile(可能有多个，通过实时查询来动态生成？？) --> (原素材的解压路径)calibration_object_detection_img_box 列表----> 将素材打成zip包  -->返回File流下载

        //1.找到解压路径 path

        //2.查询calibration_object_detection_img_box（查询个人标注的图片素材），从而更新解压路径下的json.txt文件（重点）
        List<CalibrationImgDetectDto> imgList = calibrationObjectDetectionImgBoxService.findCompletedByCalibrationIdAndFinisher(finisher, calibrationDto.getId());

        String fileType = calibrationDto.getTaskType();
        String creater = calibrationDto.getCreater();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String bucketDir = uploadPath + "/" + fileType + "/" + creater;

        //生成所有对应文件夹和图片,并压缩成zip
        String newZipFileName = "dataset_" + calibrationDto.getId() + "_" + uuid + ".zip";
        String datasetBaseDir = bucketDir + File.separator + "dataset_" + calibrationDto.getId() + "_" + uuid;//数据集目录
        //生成数据集zip包
        String zipFilePath = calibrationPictureCommon.createImgDetectMaterialZip(imgList, datasetBaseDir);
        logger.info("@123****:" + datasetBaseDir + "，已压缩成>>>>>>" + zipFilePath);
        //3.将素材重新打成zip包，返回文件流

        return new File(zipFilePath);
    }

    public String createImageDetailsData(CalibrationDto calibrationDto, String finisher) {
        //获取所有图片标签名和路径
        List<CalibrationImgDto> calibrationImgDtoList = calibrationImgService.findCompletedByFinisher(calibrationDto.getId(), finisher);

        //生成所有对应文件夹和图片,并压缩成zip
        String creater = calibrationDto.getCreater();
        String fileType = calibrationDto.getTaskType();
        String bucketDir = uploadPath + "/" + "NewCalibration/" + fileType + "/" + creater + "/" + UUID.randomUUID().toString().replaceAll("-", "");
        String resultFilePath = calibrationPictureCommon.createResultFile(calibrationImgDtoList, bucketDir);
        return resultFilePath;
    }

    public File createTxtDetailsData(CalibrationDto calibrationDto, String finisher) {
        List<CalibrationTxtDto> hasCalibratedTxt = calibrationTxtService.searchHasCalibratedByIdsAndFinisher(
                calibrationDto.getId(), finisher);
        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + ".txt";

        String creater = calibrationDto.getCreater();
        String taskType = calibrationDto.getTaskType();

        File outFile = new File(uploadPath + "/" + "NewCalibration/" + taskType + "/" + creater);
        boolean results = outFile.mkdirs();
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        outFile = new File(uploadPath + "/" + "NewCalibration/" + taskType + "/" + creater + "/" + otherName);

        Writer out;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile, true), StandardCharsets.UTF_8), 10240);
            out.write("comment" + "\t" + "label" + "\r\n");
            for (int i = 0; i < hasCalibratedTxt.size(); i++) {
                out.write(
                        hasCalibratedTxt.get(i).getTxtContent() +
                                "\t" + hasCalibratedTxt.get(i).getClassifyName()
                                + "\r\n");
//				out.write("\r\n");
            }
            out.flush();
            out.close();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        return outFile;
    }

    public String createVoiceDetailsData(CalibrationDto calibrationDto, String finisher) {
        //获取所有图片标签名和路径
        List<CalibrationVoiceDto> calibrationVoiceDtoList = calibrationVoiceService.findCompletedByFinisher(calibrationDto.getId(), finisher);

        //生成所有对应文件夹和图片,并压缩成zip
        String creater = calibrationDto.getCreater();
        String fileType = calibrationDto.getTaskType();
        String bucketDir = uploadPath + "/" + "NewCalibration/" + fileType + "/" + creater + "/" + UUID.randomUUID().toString().replaceAll("-", "");
        String resultFilePath = calibrationVoiceCommon.createResultFile(calibrationVoiceDtoList, bucketDir);
        return resultFilePath;
    }

    public File createTxtEntityDetailsData(CalibrationDto calibrationDto, String finisher) {
        List<CalibrationTxtEntityDto> hasCalibratedTxt = calibrationTxtEntityService.searchHasCalibratedByIdsAndFinisher(
                calibrationDto.getId(), finisher);
        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + ".txt";

        String creater = calibrationDto.getCreater();
        String taskType = calibrationDto.getTaskType();

        File outFile = new File(uploadPath + "/" + "NewCalibration/" + taskType + "/" + creater);
        boolean results = outFile.mkdirs();
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        outFile = new File(uploadPath + "/" + "NewCalibration/" + taskType + "/" + creater + "/" + otherName);

        Writer out;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile, true), StandardCharsets.UTF_8), 10240);
            out.write("comment" + "\t" + "result" + "\r\n");
            for (CalibrationTxtEntityDto calibrationTxtEntityDto : hasCalibratedTxt) {
                out.write(
                        calibrationTxtEntityDto.getTxtContent() +
                                "\t" + calibrationTxtEntityDto.getTxtJson()
                                + "\r\n");
//				out.write("\r\n");
            }
            out.flush();
            out.close();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        return outFile;
    }

    // 保存上传的数据信息到数据库
    public MaterialInfoDto saveData(MaterialInfoDto materialInfoDto, MultipartFile file, String creater,
                                    String bucketName, String fileType) {

        String fileName = file.getOriginalFilename();
        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + fileName.substring(fileName.lastIndexOf("."));
        String newName = fileType + "/" + creater + "/" + otherName;

//			String bucketDir="D:/upload_test"+"/"+fileType+"/"+creater;
        String bucketDir = bucketName + "/" + fileType + "/" + creater;

        if (fileName.toLowerCase().endsWith(".txt") || fileName.toLowerCase().endsWith(".csv")) {
            OutputStreamWriter os = null;
            InputStreamReader inputStream = null;
            try {
                String encode = getEncode(file);
                inputStream = new InputStreamReader(file.getInputStream(), encode);
                // 2、保存到临时文件
                // 1K的数据缓冲
                char[] bs = new char[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流保存到本地文件
                File tempFile = new File(bucketDir);
                boolean results = tempFile.mkdirs();
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                os = new OutputStreamWriter(new FileOutputStream(tempFile.getPath() + File.separator + otherName), StandardCharsets.UTF_8);
                // 开始读取
                while ((len = inputStream.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 完毕，关闭所有链接
                try {
                    os.flush();
                    os.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            OutputStream os = null;
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
                // 2、保存到临时文件
                // 1K的数据缓冲
                byte[] bs = new byte[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流保存到本地文件
                File tempFile = new File(bucketDir);
                boolean results = tempFile.mkdirs();
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                os = new FileOutputStream(tempFile.getPath() + File.separator + otherName);
                // 开始读取
                while ((len = inputStream.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 完毕，关闭所有链接
                try {
                    os.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        materialInfoDto.setBucketDir(bucketDir);
        materialInfoDto.setFileType(fileType);
        materialInfoDto.setFileName2(otherName);
        materialInfoDto.setCreater(creater);
//				materialInfoDto.setFileDesc(materialInfoDto.getFileDesc());
        materialInfoDto.setFileSize(Long.toString(file.getSize()));
        return materialInfoService.save(materialInfoDto);
    }

    // 保存上传的数据信息到数据库
    public MaterialInfoDto saveData2(MaterialInfoDto materialInfoDto, MultipartFile file, String creater,
                                     String bucketName, String fileType, ProjectDto projectDto) {

        String fileName = file.getOriginalFilename();
        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + fileName.substring(fileName.lastIndexOf("."));
        String newName = fileType + "/" + creater + "/" + otherName;

//			String bucketDir="D:/upload_test"+"/"+fileType+"/"+creater;
        String bucketDir = bucketName + "/" + fileType + "/" + creater;

        if (fileName.toLowerCase().endsWith(".txt") || fileName.toLowerCase().endsWith(".csv")) {
            OutputStreamWriter os = null;
            InputStreamReader inputStream = null;
            try {
                String encode = getEncode(file);
                inputStream = new InputStreamReader(file.getInputStream(), encode);
                // 2、保存到临时文件
                // 1K的数据缓冲
                char[] bs = new char[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流保存到本地文件
                File tempFile = new File(bucketDir);
                boolean results = tempFile.mkdirs();
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                os = new OutputStreamWriter(new FileOutputStream(tempFile.getPath() + File.separator + otherName), StandardCharsets.UTF_8);
                // 开始读取
                while ((len = inputStream.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 完毕，关闭所有链接
                try {
                    os.flush();
                    os.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            OutputStream os = null;
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
                // 2、保存到临时文件
                // 1K的数据缓冲
                byte[] bs = new byte[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流保存到本地文件
                File tempFile = new File(bucketDir);
                boolean results = tempFile.mkdirs();
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                os = new FileOutputStream(tempFile.getPath() + File.separator + otherName);
                // 开始读取
                while ((len = inputStream.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 完毕，关闭所有链接
                try {
                    os.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        materialInfoDto.setBucketDir(bucketDir);
        materialInfoDto.setFileType(fileType);
        materialInfoDto.setFileName2(otherName);
        materialInfoDto.setCreater(creater);
        materialInfoDto.setFileSize(Long.toString(file.getSize()));
        MaterialInfoDto materialInfoDtoNew = materialInfoService.save(materialInfoDto);
        projectDto.setFileId(materialInfoDtoNew.getId());
        projectService.update(projectDto);
        return materialInfoDtoNew;
    }

    // 保存上传的数据信息到数据库
    public CalibrationDto saveTxtData(CalibrationDto calibrationDto, MultipartFile file,
                                      String finisher) {
        //素材ID
        List<Long> idList = new ArrayList<>();
        //保存素材信息,以及本地文件夹
        CalibrationFileDto calibrationFileDto = saveUploadTxtInfo(file, calibrationDto);
        //分割本文素材
        divisionTxt(calibrationDto, calibrationFileDto, file, finisher);
        return calibrationDto;
    }

    // 保存上传的数据信息到数据库
    public CalibrationDto saveTxtEntity(CalibrationDto calibrationDto, MultipartFile file,
                                        String finisher) {

        //保存素材信息,以及本地文件夹
        CalibrationFileDto calibrationFileDto = calibrationTxtCommon.saveTxtInfo(file, calibrationDto);

        //分割本文素材
        calibrationTxtCommon.divideTxt(calibrationDto, calibrationFileDto, file, finisher);

        return calibrationDto;
    }

    // 保存上传的数据信息到数据库
    public CalibrationDto saveImageDectionData(CalibrationDto calibrationDto, MultipartFile file, String finisher) throws Exception {
        //保存上传的素材zip包到文件系统，保存CalibrationFile对象
        CalibrationFileDto calibrationFileDto = calibrationPictureCommon.saveZip(file, calibrationDto);
        //解压和划分图片接受人
        //calibrationPictureService.unzipAndSavePicture(calibrationDto,calibrationFileDto, finisher);
        //解压zip包，处理图片信息
        return calibrationPictureCommon.unzipAndSaveObjectDetectionPicture(calibrationDto, calibrationFileDto, finisher);
    }

    // 保存上传的数据信息到数据库
    public CalibrationDto saveImageData(CalibrationDto calibrationDto, MultipartFile file, String finisher) throws Exception {

        //保存素材信息,以及本地文件夹
        CalibrationFileDto calibrationFileDto = calibrationPictureCommon.saveZip(file, calibrationDto);

        //解压、缩略图和划分图片接受人、接收任务
        calibrationPictureCommon.unzipAndSavePicture(calibrationDto, calibrationFileDto, finisher);

        return calibrationDto;
    }


//		/**
//         * 删除数据文件
//         *
//         * @param Datas
//         * @return
//         */
//	public void deleteDataFile(List<MaterialInfoDto> Datas) {
//		// 1.oss 删除文件
//		for (MaterialInfoDto dto : Datas) {
//			try {
//				minioUtil.removeObject(dto.getFileType(), dto.getFileName2());
//			}catch (Exception e){
//				e.printStackTrace();
//			}
//		}
//	}

    // 保存上传的数据信息到数据库
    public CalibrationDto saveVoiceData(CalibrationDto calibrationDto, MultipartFile file, String finisher) throws Exception {
        //保存素材信息,以及本地文件夹
        CalibrationFileDto calibrationFileDto = calibrationPictureCommon.saveZip(file, calibrationDto);
        //解压、声音时长和划分声音接受人、接收任务
        calibrationVoiceCommon.unzipAndSaveVoice(calibrationDto, calibrationFileDto, finisher);
        return calibrationDto;
    }

    private CalibrationTxtDto generate(String content, Long id, Long uploadTxtId, String creater) {
        CalibrationTxtDto dto = new CalibrationTxtDto();
        dto.setTxtContent(content);
        dto.setCalibrationId(id);
        dto.setCreater(creater);
        dto.setCompleted("0");
        dto.setCalibrationFileId(uploadTxtId);
        return dto;
    }

	/**
	 * 数据标注：分割本文素材
	 * @param calibrationDto
	 * @param calibrationFileDto
	 * @param multipartFiles
	 * @param finisher
	 */
    private void divisionTxt(CalibrationDto calibrationDto, CalibrationFileDto calibrationFileDto, MultipartFile multipartFiles, String finisher) {
        BufferedReader reader = null;
        List<CalibrationTxtDto> calibrationTxtList = new ArrayList<>(); //以分隔符分割的素材
        try {
            StringBuilder lastLine = new StringBuilder(); //换行拼接的素材
//            for (int k = 0; k < multipartFiles.length; k++) {
            lastLine.delete(0, lastLine.length());
            //保存上传素材信息,返回id
            Long uploadTxtId = calibrationFileDto.getId();
            String creater = calibrationDto.getCreater();
            String encode = getEncode(multipartFiles);
            if ("".equals(encode)) {
                encode = "UTF-8";
                logger.error(multipartFiles.getName() + " 编码检测错误；");
            }
            reader = new BufferedReader(new InputStreamReader(multipartFiles.getInputStream(), encode));
            String line = "";

            while (StringUtils.isNotBlank(line = reader.readLine())) {
//               System.out.println(line);
//				String line2 = line.trim();
				/*
				String line2 = line;
				String[] spiltStr = line2.trim().split(REGEX);//同一行以分隔符分割的文本数组
				int num = line.trim().length() - line.trim().replace(REGEX, "").length();//分割符个数
				System.out.println(spiltStr[0]);
				System.out.println(num);
				if (num == 0) {
					System.out.println(spiltStr[0]);
					lastLine.append(spiltStr[0]);
				} else if (num == 1) {
					if (line2.endsWith(REGEX)) { //以分号结尾
						System.out.println(spiltStr[0]);
						if (StringUtils.isBlank(lastLine.toString())) {
							calibrationTxtList.add(generate(subStringContent(spiltStr[0]), calibrationDto.getId(), uploadTxtId,creater));
						} else {
							calibrationTxtList.add(generate(subStringContent(lastLine.append(spiltStr[0]).toString()), calibrationDto.getId(), uploadTxtId,creater));
							lastLine.delete(0, lastLine.length());
						}
					} else {  //不以分号结尾
						System.out.println(spiltStr[0]);
						if (StringUtils.isBlank(lastLine.toString())) {
							calibrationTxtList.add(generate(subStringContent(spiltStr[0]), calibrationDto.getId(), uploadTxtId,creater));
						} else {
							calibrationTxtList.add(generate(subStringContent(lastLine.append(spiltStr[0]).toString()), calibrationDto.getId(), uploadTxtId,creater));
							lastLine.delete(0, lastLine.length());
						}
						lastLine.append(spiltStr[1]);
					}
				} else { //多个分隔符
					for (int i = 0; i < spiltStr.length; i++) {
						if (i == 0) { //第一组判断上一行是否为空
							if (StringUtils.isBlank(lastLine.toString())) {
								calibrationTxtList.add(generate(subStringContent(spiltStr[i]), calibrationDto.getId(), uploadTxtId,creater));
							} else {
								calibrationTxtList.add(generate(subStringContent(lastLine.append(spiltStr[i]).toString()), calibrationDto.getId(), uploadTxtId,creater));
								lastLine.delete(0, lastLine.length()); //清空上一个素材内容
							}
						} else if (i == (spiltStr.length -1) && !((line2.endsWith(REGEX)))) { //最后组的判断,且不以分号结尾
							lastLine.append(spiltStr[i]).toString();
						} else {
							calibrationTxtList.add(generate(subStringContent((spiltStr[i])), calibrationDto.getId(), uploadTxtId,creater));
						}
					}
				}
*/
                calibrationTxtList.add(generate(subStringContent(line), calibrationDto.getId(), uploadTxtId, creater));
            }

            //如果本文结尾没有分号，执行该逻辑：记录一个分号到文本结尾的内容
            if (StringUtils.isNotBlank(lastLine.toString())) {
                calibrationTxtList.add(generate(subStringContent(lastLine.toString()), calibrationDto.getId(), uploadTxtId, creater));
            }
            //设置每个人的条数
            String[] finishers = finisher.split(",");
            int userlength = finishers.length;
            for (int i = 0; i < calibrationTxtList.size(); i++) {
                int j = i % userlength;
                calibrationTxtList.get(i).setFinisher(finishers[j]);
            }

            //保存分割后的素材
            if (!calibrationTxtList.isEmpty()) {
                calibrationTxtService.batchSave(calibrationTxtList);
            }
//            //修改关联素材信息
            List<CalibrationCountByFinisherDto> countTxtDto = calibrationTxtService.countTaskByCalibrationIds(calibrationDto.getId());
            //查询明细表的每个人的任务
            List<CalibrationDetailsDto> calibrationDetailsDto = calibrationDetailsService.searchDetailsCalibrationId(calibrationDto.getId());
//			//查询总概览的任务
//			CalibrationDto calibrationDtos=calibrationService.findById(calibrationDto.getId());
            Set<String> allPeople = new HashSet<String>();
            Set<String> oldPeople = new HashSet<String>();
            Set<String> newPeople = new HashSet<String>();

            for (int i = 0; i < countTxtDto.size(); i++)
                allPeople.add(countTxtDto.get(i).getFinisher());

            for (int i = 0; i < calibrationDetailsDto.size(); i++)
                oldPeople.add(calibrationDetailsDto.get(i).getFinisher());

            for (String a : allPeople) {
                if (!oldPeople.contains(a)) {
                    newPeople.add(a);
                }
            }
            //更新每个人的数据
            int totalCount = 0;
            int completed = 0;
            if (calibrationDetailsDto.size() == 0) {//第一次导入数据
                List<CalibrationDetailsDto> newcalibrationDetails = new ArrayList<>();
                for (int i = 0; i < finishers.length; i++) {
                    totalCount += countTxtDto.get(i).getCompleted() + countTxtDto.get(i).getUncompleted();
                    completed += countTxtDto.get(i).getCompleted();

                    CalibrationDetailsDto calibrationDetail = new CalibrationDetailsDto();
                    calibrationDetail.setCalibrationDesc(calibrationDto.getCalibrationDesc());
                    calibrationDetail.setCalibrationId(calibrationDto.getId());
                    calibrationDetail.setCalibrationName(calibrationDto.getCalibrationName());
                    calibrationDetail.setPriority(calibrationDto.getPriority());
                    calibrationDetail.setCreater(calibrationDto.getCreater());
                    calibrationDetail.setFinishedTime(calibrationDto.getFinishedTime());
                    calibrationDetail.setFinisher(countTxtDto.get(i).getFinisher());
                    // 标注中
                    calibrationDetail.setStatus(CalibrationConstant.TASK_STATUS_CALIBRATING);
                    calibrationDetail.setCompleted(0);// 已标注数量
                    calibrationDetail.setTaskType(calibrationDto.getTaskType());
                    calibrationDetail.setCreateTime(new Date());
                    calibrationDetail.setClassifyCount(0);  // 标签数量
                    calibrationDetail.setTotalCount(countTxtDto.get(i).getCompleted() + countTxtDto.get(i).getUncompleted());
                    newcalibrationDetails.add(calibrationDetail);
                }
                calibrationDetailsService.batchSave(newcalibrationDetails);
            } else {//添加数据的情况
                List<CalibrationDetailsDto> calibrationDetails = new ArrayList<>(); //
                Integer classifyCount = calibrationDetailsDto.get(0).getClassifyCount();

                for (int i = 0; i < countTxtDto.size(); i++) {//所有人的
                    totalCount += countTxtDto.get(i).getCompleted() + countTxtDto.get(i).getUncompleted();
                    completed += countTxtDto.get(i).getCompleted();

                    if (newPeople.contains(countTxtDto.get(i).getFinisher())) {//新分配的人
                        CalibrationDetailsDto calibrationDetail = new CalibrationDetailsDto();
                        calibrationDetail.setCalibrationDesc(calibrationDto.getCalibrationDesc());
                        calibrationDetail.setCalibrationId(calibrationDto.getId());
                        calibrationDetail.setCalibrationName(calibrationDto.getCalibrationName());
                        calibrationDetail.setPriority(calibrationDto.getPriority());
                        calibrationDetail.setCreater(calibrationDto.getCreater());
                        calibrationDetail.setFinishedTime(calibrationDto.getFinishedTime());
                        calibrationDetail.setFinisher(countTxtDto.get(i).getFinisher());
                        calibrationDetail.setStatus(CalibrationConstant.TASK_STATUS_CALIBRATING);
                        calibrationDetail.setCompleted(0);
                        calibrationDetail.setTaskType(calibrationDto.getTaskType());
                        calibrationDetail.setCreateTime(new Date());
                        calibrationDetail.setClassifyCount(classifyCount);
                        calibrationDetail.setTotalCount(countTxtDto.get(i).getCompleted() + countTxtDto.get(i).getUncompleted());
                        calibrationDetails.add(calibrationDetail);
                    } else {//不是新人
                        for (CalibrationDetailsDto detailsDto : calibrationDetailsDto) {
                            if (detailsDto.getFinisher().equals(countTxtDto.get(i).getFinisher())) {
                                if (countTxtDto.get(i).getUncompleted() == 0) {//如果全部完成
                                    detailsDto.setStatus(CalibrationConstant.TASK_STATUS_COMPLETED);
                                    detailsDto.setCompleted(countTxtDto.get(i).getCompleted());
                                    detailsDto.setTotalCount(countTxtDto.get(i).getCompleted() + countTxtDto.get(i).getUncompleted());
                                } else {
                                    detailsDto.setStatus(CalibrationConstant.TASK_STATUS_CALIBRATING);
                                    detailsDto.setCompleted(countTxtDto.get(i).getCompleted());
                                    detailsDto.setTotalCount(countTxtDto.get(i).getCompleted() + countTxtDto.get(i).getUncompleted());
                                }
                                calibrationDetailsService.update(detailsDto);
                            }
                        }

                    }
                }
                calibrationDetailsService.batchSave(calibrationDetails);
            }
            //更新总览的数据
            calibrationDto.setTotalCount(totalCount);
            calibrationDto.setCompleted(completed);
            if (totalCount != completed) calibrationDto.setStatus(CalibrationConstant.TASK_STATUS_CALIBRATING);
            calibrationService.update(calibrationDto);

            if (reader != null) {
                reader.close();
            }
        } catch (Exception e) {
            logger.error("文本分割异常 {}", e.toString());
        }
    }

    private String subStringContent(String content) {
        if (content.length() > 256) {
            return content.substring(0, 256);
        }
        return content;
    }

    private String getEncode(MultipartFile multipartFile) {

        String str = "";
        String encode = "UTF-8";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(multipartFile.getInputStream(), encode));
            str = br.readLine() + br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (!isMessyCode(str)) {
            return encode;
        }

        encode = "GB2312";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(multipartFile.getInputStream(), encode));
            str = br.readLine() + br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (!isMessyCode(str)) {
            return encode;
        }

        encode = "GBK";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(multipartFile.getInputStream(), encode));
            str = br.readLine() + br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (!isMessyCode(str)) {
            return encode;
        }

        encode = "ISO-8859-1";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(multipartFile.getInputStream(), encode));
            str = br.readLine() + br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (!isMessyCode(str)) {
            return encode;
        }
        return "";
    }

    /**
     * 数据标注，文本模式分类
     * 上传文件
     *
     * @param file
     * @param calibrationDto
     * @return
     */
    private CalibrationFileDto saveUploadTxtInfo(MultipartFile file, CalibrationDto calibrationDto) {

        String fileName = file.getOriginalFilename();
        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + fileName.substring(fileName.lastIndexOf("."));

        String fileType = calibrationDto.getTaskType();
        String creater = calibrationDto.getCreater();
        String bucketDir = uploadPath + "/" + "calibration" + "/" + fileType + "/" + creater;
        OutputStream os = null;
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            // 2、保存到临时文件，1K的数据缓冲
            byte[] bs = new byte[1024];
            int len;// 读取到的数据长度
            File tempFile = new File(bucketDir); // 输出的文件流保存到本地文件
            boolean results = tempFile.mkdirs();
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + otherName);
            while ((len = inputStream.read(bs)) != -1) {// 开始读取
                os.write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {// 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

//		CalibrationDto news=calibrationService.save(calibrationDto);
//        CalibrationDetails calibrationDetails=new CalibrationDetails();
        CalibrationFileDto calibrationFiles = new CalibrationFileDto();
        if (calibrationDto.getId() != null) {
            CalibrationFileDto calibrationFile = new CalibrationFileDto();
            calibrationFile.setBucketDir(bucketDir);
            calibrationFile.setCalibrationId(calibrationDto.getId());
            calibrationFile.setFileName(fileName);
            calibrationFile.setFileName2(otherName);

            calibrationFiles = calibrationFileService.save(calibrationFile);

        } else {
            return null;
        }
        return calibrationFiles;
    }


//	//根据文件的前三个字节来判断编码
//	public static String codeString(MultipartFile file) throws Exception {
//		BufferedInputStream bin = new BufferedInputStream(file.getInputStream());
//		int p = (bin.read() << 8) + bin.read();
//		bin.close();
//		String code = null;
//
//		switch (p) {
//			case 0xefbb:
//				code = "UTF-8";
//				break;
//			case 0xfffe:
//				code = "Unicode";
//				break;
//			case 0xfeff:
//				code = "UTF-16BE";
//				break;
//			case 0x5c75:
//				code = "ANSI|ASCII" ;
//				break ;
//			default:
//				code = "GBK";
//		}
//
//		return code;
//	}

//	/**
//	 * 利用第三方开源包cpdetector获取文件编码格式
//	 */
//	public String getFileEncode(MultipartFile file) {
//		/*
//		 * detector是探测器，它把探测任务交给具体的探测实现类的实例完成。
//		 * cpDetector内置了一些常用的探测实现类，这些探测实现类的实例可以通过add方法 加进来，如ParsingDetector、
//		 * JChardetFacade、ASCIIDetector、UnicodeDetector。
//		 * detector按照“谁最先返回非空的探测结果，就以该结果为准”的原则返回探测到的
//		 * 字符集编码。使用需要用到三个第三方JAR包：antlr.jar、chardet.jar和cpdetector.jar
//		 * cpDetector是基于统计学原理的，不保证完全正确。
//		 */
//		CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
//		/*
//		 * ParsingDetector可用于检查HTML、XML等文件或字符流的编码,构造方法中的参数用于
//		 * 指示是否显示探测过程的详细信息，为false不显示。
//		 */
//		detector.add(new ParsingDetector(false));
//		/*
//		 * JChardetFacade封装了由Mozilla组织提供的JChardet，它可以完成大多数文件的编码
//		 * 测定。所以，一般有了这个探测器就可满足大多数项目的要求，如果你还不放心，可以
//		 * 再多加几个探测器，比如下面的ASCIIDetector、UnicodeDetector等。
//		 */
//		detector.add(JChardetFacade.getInstance());// 用到antlr.jar、chardet.jar
//		// ASCIIDetector用于ASCII编码测定
//		detector.add(ASCIIDetector.getInstance());
//		// UnicodeDetector用于Unicode家族编码的测定
//		detector.add(UnicodeDetector.getInstance());
//		java.nio.charset.Charset charset = null;
////        File f = new File(path);
//		try {
//			BufferedInputStream in = new BufferedInputStream(file.getInputStream());
////            charset = detector.detectCodepage(f.toURI().toURL());
//			charset = detector.detectCodepage(in,2147483647);
////            charset = codeTest(in,2147483647);
//			System.out.println(charset);
//		} catch (Exception ex) {
//			ex.printStackTrace();
//		}
//		if (charset != null)
//			return charset.name();
//		else
//			return null;
//	}

}
